package com.assets.Fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.assets.Adapter.Public_list_item_Adapter;
import com.assets.bean.Lease_bean;
import com.assets.lease.Lease_add;
import com.assets.lease.Lease_lv;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.demo.WaveSwipeRefreshLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/12/25.
 */

public class Fragment5 extends Fragment {
    private ImageView imageView,screen,add;
    private String url ="http://"+ Url.IP+"/api/leaseQuery";//上传
    private ListView lv_list;
    private SlideSideMenuExampleActivity content;
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_second5, null);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        content = (SlideSideMenuExampleActivity) getActivity();
        init();
    }

    private void init() {
        lv_list = (ListView) getActivity().findViewById(R.id.fragment2_list);
        imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
        add = (ImageView) content.findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(content, Lease_add.class);
                startActivity(intent);
            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SlideSideMenuTransitionLayout mSlideSideMenu= (SlideSideMenuTransitionLayout)getActivity().findViewById(R.id.slide_side_menu);
                mSlideSideMenu.toggle();
            }
        });
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {

                    Intent intent = new Intent(content, Lease_lv.class);
                    intent.putExtra("leaseid", String.valueOf(list.get(i).get("odd")));
                    intent.putExtra("person", String.valueOf(list.get(i).get("sum")));
                    intent.putExtra("status", String.valueOf(list.get(i).get("scope")));
                    intent.putExtra("money", String.valueOf(list.get(i).get("creator")));
                    intent.putExtra("return_date", String.valueOf(list.get(i).get("state")));
                    intent.putExtra("time", String.valueOf(list.get(i).get("Date_created")));
                    intent.putExtra("loan_date", String.valueOf(list.get(i).get("Inventory_date")));
                    startActivity(intent);

            }
        });
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {//模拟3秒的加载过程
                    @Override
                    public void run() {
                        load();
                        //接下来可以刷新ListView
                    }
                }, 1200);


            }

        });
    }

    @Override
    public void onStart() {
        Timer timer=new Timer();//实例化Timer类
        timer.schedule(new TimerTask(){
            public void run(){
                load();
                this.cancel();
            }
        },300);//五百毫秒

        super.onStart();
    }
    private void load() {
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", Since_case.getInstance().getUserId())
                            .build();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("222",responseData.toString());
                    showResponse(responseData);

                } catch (IOException e) {
                    e.printStackTrace();

                }


            }
        }.start();
    }
    private void showResponse(final String responseData) {
        content.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (responseData.equals("[]")){
                    Toast.makeText(content,"无租赁记录",Toast.LENGTH_SHORT).show();
                }
                list.clear();
                mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
                Gson gson = new Gson();
                List<Lease_bean> userList = gson.fromJson(responseData, new TypeToken<List<Lease_bean>>(){}.getType());
                for(int i = 0;i < userList.size();i++){
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("odd_tv","租赁单号");
                    map.put("creator_tv","金额");
                    map.put("sum_tv","租赁人");
                    map.put("state_tv","预计归还");
                    map.put("scope_tv","状态");
                    map.put("Date_created_tv","申请时间");
                    map.put("Inventory_date_tv","借出时间");


                    map.put("odd",userList.get(i).getLeaseId());
                    map.put("Date_created",userList.get(i).getRedate().substring(0,10));
                    map.put("creator",userList.get(i).getLeaseAmount());
                    map.put("sum",userList.get(i).getLeaseUser());
                    if (userList.get(i).getLeaseDate().equals("")){
                        map.put("Inventory_date",userList.get(i).getLeaseDate());
                    }else {
                        map.put("Inventory_date",userList.get(i).getLeaseDate().substring(0,10));
                    }
                    map.put("scope",userList.get(i).getStatus());
                    if (userList.get(i).getLeaseTime().equals("")){
                        map.put("state",userList.get(i).getLeaseTime());
                    }else {
                        map.put("state",userList.get(i).getLeaseTime().substring(0,10));
                    }
                    list.add(0,map);
                }
                Public_list_item_Adapter re_ad = new Public_list_item_Adapter(content,list);
                lv_list.setAdapter(re_ad);
            }
        });
    }
}
